<template>
  <div class="custom-card-box">
    <customCard :width="280"  :height="230"  class="custom-card-user" withAnimate>
      <template #title>
        您好，欢迎使用
      </template>

      <template #avatar>
        <t-avatar :image="user.avatarUrl" size="40px"></t-avatar>
      </template>

      <template #content>
        <div class="custom-card-user-content">
          <p class="ellipsis-1 div-NoWrap"><span>当前用户: </span>{{user.name ? user.name : '暂无' }}</p>
          <p class="ellipsis-1 div-NoWrap"><span>所属部门: </span>{{user.deptName ? user.deptName : '暂无'}}</p>
          <p class="ellipsis-1 div-NoWrap"><span>当前日期: </span>{{dates.getCurrentDate('yyyy年MM月dd日')}}</p>
          <p class="ellipsis-1 div-NoWrap"><span>PC版本: </span>{{ cpVersionInfo.versionWeb ? cpVersionInfo.versionWeb : '暂无'}}</p>
          <p class="ellipsis-1 div-NoWrap"><span>API版本: </span>{{cpVersionInfo.versionApi ? cpVersionInfo.versionApi : '暂无'}}</p>
        </div>
      </template>
    </customCard>

    <customCard  withAnimate :width="280" :height="230" class="custom-card-quick-menu">
      <template #title>
        <Icon class="card-icon" name="heart-filled" style="color: #fe494b" />
        <span style="vertical-align: middle">快捷操作({{workbenchListMenu.length}})</span>
      </template>
      <template #actions>
        <customSpace>
          <template #content>
            <customButton @click="getMenuQuickList(true)"  title="刷新" theme="success" size="small" help="刷新数据"/>
            <customButton @click="$refs.setMenuQuick.show()"  title="设置" theme="primary" size="small" help="设置快捷操作"/>
          </template>
        </customSpace>
      </template>
      <template #content>
        <div :class="'menu-list ' + (workbenchListMenu.length > 10 && 'menu-list-height')"  >
          <div
            class="content"
            v-for="(ob, index) in workbenchListMenu"
            :key="ob.id"
            @click="utils.openMenu(ob.url)"
          >
            <i
              :class="strings.defaultIfBlank(ob.icon, 'layui-icon layui-icon-set') "
              :style="'color: ' + ob.iconColor"
            ></i>
            <p>{{ ob.name }}</p>
          </div>
          <p class="empty" v-if="workbenchListMenu.length < 1">尚未配置</p>
        </div>
      </template>
    </customCard>

    <customCard  withAnimate :height="230" :width="350" style="width: calc(100% - 593px ); margin-right: 0px">
      <template #title>
        <Icon class="card-icon" name="view-module" style="color: #0099ff" />
        <span style="vertical-align: middle">公告信息</span>
      </template>
<!--      <template #actions>
        <customSpace>
          <template #content>
            <customButton @click="utils.openMenu('innernotice')"  title="历史公告" theme="primary" size="small" help="查看历史公告"/>
          </template>
        </customSpace>
      </template>-->
      <template #content>
        <div :class="'systemnotice-box ' + (workbenchListNews.length > 2 && 'systemnotice-box-height')">
          <div v-for="(ob, index) in workbenchListNews" :key="ob.id" class="systemnotice-item" :index="index">
            <div class="title">{{ ob.title }}</div>
            <div class="time">
              <i class="el-icon-time"></i>{{ new Date(ob.gmtSend).format('yyyy-MM-dd HH:mm:ss') }}
            </div>
            <div class="content" v-html="ob.content">{{ ob.content }}</div>
          </div>
          <p v-if="workbenchListNews.length < 1" class="empty">暂无信息</p>
        </div>
      </template>
    </customCard>


    <customCard class="num-count-card"  withAnimate style="width: 280px; text-align: center" :height="500">
      <template #title>
        <Icon class="card-icon" name="image" style="color: #409eff" />
        <span style="vertical-align: middle">基础信息统计</span>
      </template>
      <template #actions>
        <customSpace>
          <template #content>
            <customButton @click="getCountInfoBase(true)"  title="刷新" theme="success" size="small" help="刷新统计数据"/>
          </template>
        </customSpace>
      </template>
      <template #content >
        <div class="custom-statistic-container">
          <customStatistic
            v-for="(item,index) in Object.values(cardData.countInfoBase)"
            :key="index"
            :title="item.title"
            :value="item.value"
            :unit="item.unit"
            :color="item.color"
            :extra="item.extra"
            trend="increase"
            :width="strings.defaultIfBlank(item.width, '122px')"
            height="120px"
            :class="'num-count-show-' + item.show"
            :marginRight="item.marginRight"
            v-if="item.show == 1"
          />
        </div>
      </template>
    </customCard>

    <customCard class="num-count-card"  withAnimate style="width: 280px; text-align: center" :height="500">
      <template #title>
        <Icon class="card-icon" name="image" style="color: #409eff" />
        <span style="vertical-align: middle">业务统计</span>
      </template>
      <template #actions>
        <customSpace>
          <template #content>
            <customButton @click="getCountInfoBus(true)"  title="刷新" theme="success" size="small" help="刷新统计数据"/>
          </template>
        </customSpace>
      </template>
      <template #content >
        <div class="custom-statistic-container">
          <customStatistic
            v-for="(item,index) in Object.values(cardData.countInfoBus)"
            :key="index"
            :title="item.title"
            :value="item.value"
            :unit="item.unit"
            :color="item.color"
            :extra="item.extra"
            trend="increase"
            :width="strings.defaultIfBlank(item.width, '122px')"
            height="120px"
            :class="'num-count-show-' + item.show"
            :marginRight="item.marginRight"
          />
        </div>
      </template>
    </customCard>

    <customCard   style="width: calc(100% - 593px); margin-right: 0px"   :height="500">
      <template #title>
        <Icon class="card-icon" name="add-rectangle" style="color: #e6a23c" />
        <span style="vertical-align: middle">待办任务({{cardData.taskTodoSize}})</span>
      </template>
      <template #content>
        <taskTodo ref="taskTodo" @setSize="(taskTodoSize) => cardData.taskTodoSize  = taskTodoSize"/>
      </template>
    </customCard>


    <customCard style="width: 100%;"  :height="560" class="custom-card-iframe" v-if="utils.isAdmin()">
      <template #title>
        <Icon class="card-icon" name="notification-filled" style="color: #fe9124" />
        <span style="vertical-align: middle">消息推送情况</span>
      </template>
      <template #content>
        <pushedRecordIndex :propPageSize="8"/>
      </template>
    </customCard>


    <setMenuQuick ref="setMenuQuick" @change="getMenuQuickList"/>
  </div>
</template>

<script>
/* eslint-disable */
import { Icon } from 'tdesign-icons-vue'
import customCard from '@/components/custom/layout/customCard'
import customList from '@/components/custom/layout/customList'
import customListItem from '@/components/custom/layout/customListItem'
import customStatistic from '@/components/custom/form/customStatistic'
import Report from "@/components/report/Report.vue";
import taskTodo from "./taskTodo.vue";
import pushedRecordIndex from "@/views/sys/pushedRecord/index.vue";
import setMenuQuick from "./setMenuQuick.vue";
import utils from "@/util/utils";

export default {
  name: 'dashboard',
  data() {
    return {
      form: {
        printerServerName: ''
      },
      user: {
        name: '',
        deptName: '',
      },
      workbenchListMenu: [],
      workbenchListOther: [],
      workbenchListNews: [],

      //以下为原来工作台的属性
      warehouseName: '未设置',
      applyWarehouseName: '未设置',
      warehouseId: '',
      searchedList: [],
      warehouseList: [],
      printAuto: false,
      winH: window.innerHeight,

      //数据
      cardData: {
        //待办数量
        taskTodoSize: 0,

        //基础数据统计
        countInfoBase: {
          // 供应商数量
          spCount: {
            show: 0,
            title: '供应商',
            unit: '个',
            color: '#339999',
          },

          // 商品数量
          matrCount: {
            show: 0,
            title: '商品',
            unit: '个',
            color: '#993333',
          },

          // 生产厂家
          mfgCount: {
            show: 0,
            title: '生产厂家',
            unit: '个',
            color: '#0066CC',
          },
          // 本月增加供应商数量
          spCountAdd: {
            show: 0,
            title: '供应商新增',
            unit: '个',
            color: '#339999',
          },

          // 本月增加商品数量
          matrCountAdd: {
            show: 0,
            title: '商品新增',
            unit: '个',
            color: '#993333',
          },

          // 本月增加生产厂家
          mfgCountAdd: {
            show: 0,
            title: '厂家新增',
            unit: '个',
            color: '#0066CC',
          }
        },

        //业务数据统计
        countInfoBus: {
          // 订单待确认
          orderStartCount: {
            show: 0,
            title: '待确认订单',
            unit: '个',
            color: '#996600',
          },
          // 待发货订单
          deliveryStartCount: {
            show: 0,
            title: '待发货订单',
            unit: '个',
            color: '#FF6666',
          },
          // 已完成订单
          orderEndCount: {
            show: 0,
            title: '已完成订单',
            unit: '个',
            color: '#99CC66',
          },
          // 资质过期
          certExpireCount: {
            show: 0,
            title: '资质预警',
            unit: '个',
            color: '#9933FF',
          },
          // 已完成开票金额
          invoiceEndAmount: {
            show: 0,
            title: '已完成开票金额',
            unit: '元',
            color: '#0066CC',
            width: '100%',
            marginRight: '0 !important'
          },
        }
      },
    }
  },
  created() {
  },
  watch: {
    // 用户状态改变，更新打印设置
    '$store.state.users.userState': {
      immediate: true, // 初始创建 watch 时立即执行回调函数
      deep: true, // 监听到对象里面的值的变化
      handler() {
        this.setPrint()
      },
    },
  },
  components: {
    Report,
    Icon,
    customCard,
    customList,
    customListItem,
    customStatistic,
    taskTodo,
    setMenuQuick,
    pushedRecordIndex
  },
  computed: {
    utils() {
      return utils
    },
    cpParentTitle() {
      return this.strings.defaultIfBlank(this.form.applyWarehouseName, '未设置')
    },
    cpMsgWrapper() {
      let _wrapper = this.$newWrapper()
      _wrapper.eq('contentType', 'news')
      _wrapper.orderBy('gmtSend')
      return _wrapper
    },
    // 版本信息
    cpVersionInfo() {
      let versionInfo = {
        versionWeb: '无',
        versionApi: '无',
        customIp: '无'
      }
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      versionInfo.versionApi = userInfo.versionApi
      versionInfo.versionWeb = global.settings.versionWeb

      return versionInfo
    }
  },
  methods: {
    //初始化工作区
    initWorkbench() {
      //获取用户仓库
      this.getByCurrentUser()

      //获取当前用户公告信息
      this.$ajax.get('sys/workbench/listNews').then((response) => {
        if (response.code == 0 && response.data && response.data.length > 0) {
          response.data.forEach((item) => this.workbenchListNews.push(item))
        }
      })
    },

    //选择打印服务器
    choicePrintServer(type) {
      if (type == 'label') {
        let param = {
          type: 'set',
        }
        global.utilPrint.openLabel(param)
        return
      }

      let param = {
        that: this, //当前调用对象
        isSet: true, //设置
      }
      global.utilPrint.openFormPrint(param)
    },

    //设置打印机
    setPrint() {
      //表单打印机名称
      const _printerFormName = this.utils.loadUserState(this, 'printerFormName')
      this.printer_form_name = _printerFormName
      this.$set(this.form, 'printer_form_name', _printerFormName)
      //表单打印机是否自动打印
      this.printAuto = this.utils.loadUserState(this, 'printerFormPrintAuto', null, true)

      //标签打印机名称
      let printerLabelConfig = this.utils.loadPrinterLabelConfig(this)
      if (printerLabelConfig) {
        this.$set(this.form, 'printerServerName', printerLabelConfig.printerServerName)
      }
    },


    //选择事件-仓库
    setCurrentSelect(warehouse) {
      this.setCurrent(warehouse, true)
    },


    //选择事件-仓库
    setCurrent(warehouse, isUser) {
      if (!warehouse) {
        warehouse = { id: '', name: '未配置' }
      }
      this.warehouseId = warehouse.id
      this.warehouseName = warehouse.warehouseName
      this.applyWarehouseName = warehouse.applyWarehouseName

      this.$set(this.form, 'warehouseId', warehouse.id)
      this.$set(this.form, 'warehouseName', warehouse.warehouseName)
      this.$set(this.form, 'applyWarehouseName', warehouse.applyWarehouseName)

      this.$store.commit('SET_CURRENT_WAREHOUSE', warehouse)
      if (isUser && isUser == true) {
        //更新用户状态
        global.utils.updateUserState('workbenchWarehouse', warehouse, this, true)
      }
    },

    //获取用户仓库列表
    getByCurrentUser() {
      this.$ajax.get('/base/user_warehouse/getByCurrentUser').then((res) => {
        if (res.code == 0) {
          this.warehouseList = res.data || []
          this.searchedList = this.warehouseList
          if (this.searchedList && this.searchedList.length > 0) {
            let findIndex = this.searchedList.findIndex((ob) => ob.id == this.warehouseId)
            if (findIndex != -1) {
              let findOb = this.searchedList.filter((ob) => ob.id == this.warehouseId)
              this.searchedList.splice(findIndex, 1)
              this.searchedList.unshift(findOb)
            }
          }

          let warehouse = null

          if (this.warehouseList.length == 0) {
            global.utilMessage.warning('当前用户尚未分配仓库权限，某些业务将无法操作!')
            this.setCurrent(null, false)
            return
          } else {
            if (this.utils.loadUserState(this, 'workbenchWarehouse', this.warehouseList)) return
            // let currentWarehouse = JSON.parse(localStorage.getItem('current_warehouse'))
            // //获取本地存储的仓库信息
            // if (currentWarehouse)   warehouse = this.warehouseList.find(item => item.id == currentWarehouse.id)

            //只有一个仓库则默认选中
            // let currentWarehouse
            if (this.warehouseList.length == 1) warehouse = this.warehouseList[0]

            //多个仓库获取默认仓库
            if (!warehouse) warehouse = this.warehouseList.find((item) => item.flagDefault == 1)

            if (!warehouse) {
              global.utilMessage.alertFail(
                `您有${this.warehouseList.length}个仓库权限，请自行选择，或者联系运营人员设置科室默认仓库`
              )
            }
          }
          this.setCurrent(warehouse, false)
        }
      })

      this.setPrint()
    },

    loadArea(flagType, typeKey) {
      this.$refs[typeKey][0].fetchData()
    },
    handleExtraButtonClick(extra) {
      let {
        button: { key },
      } = extra
      if (key === 'vrb-read-all') {
        if (!this.$refs.unreadDV.tablePage.totalResult) {
          this.utilMessage.warning('当前已无待处理的消息')
          return
        }
        this.utilMessage.confirm('是否全部标记为已读？', () => {
          this.$ajax.put('/msg/inner_inbox/read_all').then((resp) => {
            this.utilMessage.success(resp.msg)
            this.$refs.unreadDV.fetchData()
          })
        })
      }
    },

    // 获取统计数据-基础数据
    getCountInfoBase(hasLoad) {
      if (hasLoad) {
        this.utilVue.loadShow(true)
      }
      let getUrl = `base/workbench/getCountInfoBase`
      Object.keys(this.cardData.countInfoBase).forEach(key2 => {
        this.$set(this.cardData.countInfoBase[key2], 'value', 0)
      })

      this.$ajax.get(getUrl).then((response) => {
        if (hasLoad) {
          this.utilVue.loadHide()
          this.utilMessage.success('数据刷新完成')
        }
        if (response.code == 0) {
          Object.keys(response.data).forEach(key => {
            let countInfo = response.data[key]
            Object.keys(countInfo).forEach(key2 => {
              if (!(key2 == 'width' && this.strings.isBlank(countInfo[key2]))) {
                this.$set(this.cardData.countInfoBase[key], key2, countInfo[key2])
              }
            })
          })
        }
      })
    },

    // 获取统计数据-业务数据
    getCountInfoBus(hasLoad) {
      if (hasLoad) {
        this.utilVue.loadShow(true)
      }
      let getUrl = `base/workbench/getCountInfoBus`
      Object.keys(this.cardData.countInfoBus).forEach(key2 => {
        this.$set(this.cardData.countInfoBus[key2], 'value', 0)
      })

      this.$ajax.get(getUrl).then((response) => {
        if (hasLoad) {
          this.utilVue.loadHide()
          this.utilMessage.success('数据刷新完成')
        }
        if (response.code == 0) {
          Object.keys(response.data).forEach(key => {
            let countInfo = response.data[key]
            Object.keys(countInfo).forEach(key2 => {
              if (!(key2 == 'width' && this.strings.isBlank(countInfo[key2]))) {
                this.$set(this.cardData.countInfoBus[key], key2, countInfo[key2])
              }
            })
          })
        }
      })
    },

    // 获取快捷菜单
    getMenuQuickList(hasLoad = false) {
      if (hasLoad) {
        this.utilVue.loadShow(true)
      }
      this.workbenchListMenu = []
      if (this.user.code != 'admin') {
        this.$ajax.get('upms/shortcuts/list').then((response) => {
          if (response.code == 0) {
            if (hasLoad) {
              this.utilVue.loadHide()
              this.utilMessage.success('数据刷新完成')
            }
            if (response.data && response.data.length > 0) {
              this.workbenchListMenu = response.data
            }
            this.$refs.setMenuQuick.setUserMenuList(this.workbenchListMenu)
          }
        })
      }
    },

    // 菜单激活
    menuActiveCall() {
      this.getCountInfoBase()
      this.getCountInfoBus()
      this.$refs.taskTodo.loadData()
    }
  },
  mounted() {
    const userInfo = this.utils.getUser()
    this.user.name = userInfo.nickname
    this.user.deptName = userInfo.officeName
    this.user.deptName = userInfo.officeName
    let deptType = this.utils.getCurrentUser().deptType || ''
    let avatarUrl
    if (deptType == this.constCommon.deptType.hospital) {
      avatarUrl = require('@/assets/icon/dept/hp.jpg')
    } else if (deptType == this.constCommon.deptType.supplier) {
      avatarUrl = require('@/assets/icon/dept/sp.jpg')
    } else {
      avatarUrl = require('@/assets/icon/dept/so.jpg')
    }
    this.user.avatarUrl = avatarUrl

    setTimeout(() => {
      this.getMenuQuickList()
      this.getCountInfoBase()
      this.getCountInfoBus()
    }, 2000)
  },
}
</script>
<style lang="scss">
@import '../../styles/version1/home_dashboard.scss';
</style>
